<template>
  <div class="dashboard-container">
    <!-- 顶部公告栏 -->
    <el-alert title="系统公告：本周六凌晨2:00-4:00系统维护，请提前安排业务。" type="info" show-icon class="dashboard-announcement" />
    <h1 class="dashboard-title">喵汪云管家 - 宠物服务后台管理系统</h1>
    <div class="dashboard-main">
      <div class="dashboard-main-left">
        <!-- 统计卡片区 -->
        <div class="dashboard-cards">
          <el-card class="dashboard-card dashboard-card-blue">
            <div class="dashboard-card-title">今日订单</div>
            <div class="dashboard-card-value">{{ todayOrderCount }}</div>
            <div class="dashboard-card-desc">实时统计</div>
          </el-card>
          <el-card class="dashboard-card dashboard-card-green">
            <div class="dashboard-card-title">今日收入</div>
            <div class="dashboard-card-value">¥{{ todayIncome }}</div>
            <div class="dashboard-card-desc">实时统计</div>
          </el-card>
          <el-card class="dashboard-card dashboard-card-yellow">
            <div class="dashboard-card-title">会员总数</div>
            <div class="dashboard-card-value">{{ memberCount }}</div>
            <div class="dashboard-card-desc">实时统计</div>
          </el-card>
          <el-card class="dashboard-card dashboard-card-red">
            <div class="dashboard-card-title">库存预警</div>
            <div class="dashboard-card-value">{{ lowStockCount }}</div>
            <div class="dashboard-card-desc">低于20件</div>
          </el-card>
        </div>
        <!-- 数据趋势图 -->
        <el-card class="dashboard-chart">
          <div class="dashboard-chart-title">本周订单趋势</div>
          <div ref="orderChart" class="dashboard-echart"></div>
        </el-card>
        <!-- 快速操作区 -->
        <el-card class="dashboard-actions-card">
          <div class="dashboard-actions">
            <div class="dashboard-action-row">
              <el-button class="action-btn blue" @click="go('customer')">客户管理</el-button>
              <el-button class="action-btn green" @click="go('pet')">宠物管理</el-button>
              <el-button class="action-btn orange" @click="go('service')">服务预约</el-button>
              <el-button class="action-btn purple" @click="go('consumption')">消费记录</el-button>
            </div>
            <div class="dashboard-action-row">
              <el-button class="action-btn teal" @click="go('inventory')">库存管理</el-button>
              <el-button class="action-btn pink" @click="go('employee')">员工管理</el-button>
              <el-button class="action-btn yellow" @click="go('system')">系统设置</el-button>
              <el-button class="action-btn gray">更多功能</el-button>
            </div>
          </div>
        </el-card>
      </div>
      <!-- 右侧图片 -->
      <div class="dashboard-main-right">
        <div class="dashboard-right-col">
          <el-card class="todo-card">
            <div class="dashboard-todo-title">待办事项</div>
            <ul class="dashboard-todo-list">
              <li :class="{ highlight: highlightOrder }">
                <span class="todo-dot todo-blue"></span>
                有 <b>{{ animatedPendingOrderCount }}</b> 个订单待处理
              </li>
              <li :class="{ highlight: highlightStock }">
                <span class="todo-dot todo-red"></span>
                <b>{{ animatedLowStockCount }}</b> 个商品库存低于阈值
              </li>
              <li :class="{ highlight: highlightFeedback }">
                <span class="todo-dot todo-yellow"></span>
                <b>{{ animatedPendingFeedbackCount }}</b> 条客户反馈未回复
              </li>
              <li :class="{ highlight: highlightBirthday }">
                <span class="todo-dot todo-green"></span>
                今日有 <b>{{ animatedTodayBirthdayMemberCount }}</b> 位会员生日
              </li>
            </ul>
          </el-card>
          <img class="dashboard-side-img" src="@/assets/home.png" alt="dashboard side" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import { useOrderStore } from '@/stores/orderStore';
import { useCustomerStore } from '@/stores/customerStore';
import request from '@/utils/request';

const router = useRouter();
const orderStore = useOrderStore();
const customerStore = useCustomerStore();
const orderChart = ref(null);

// 统计今日订单数
const todayOrderCount = computed(() => {
  const today = dayjs().format('YYYY-MM-DD');
  return orderStore.orders.filter(o => dayjs(o.transactionDate).format('YYYY-MM-DD') === today).length;
});
// 统计今日收入
const todayIncome = computed(() => {
  const today = dayjs().format('YYYY-MM-DD');
  return orderStore.orders
    .filter(o => dayjs(o.transactionDate).format('YYYY-MM-DD') === today)
    .reduce((sum, o) => sum + (Number(o.actualAmount) || 0), 0);
});
// 会员总数
const memberCount = computed(() => {
  return customerStore.customers.filter(c => c.isMember).length;
});
// 库存预警
const lowStockCount = ref(0);
const fetchLowStock = async () => {
  const res = await request.post('/employee-pet/product/list', { pageNum: 1, pageSize: 10000 });
  if (res.data && Array.isArray(res.data.data)) {
    lowStockCount.value = res.data.data.filter(p => p.stock < 20).length;
  }
};

// 订单待处理数
const pendingOrderCount = computed(() => {
  return orderStore.orders.filter(o => o.status === '待处理').length;
});
// 客户反馈未回复（mock）
const pendingFeedbackCount = ref(1); // 如有反馈store可替换
// 今日会员生日数
const todayBirthdayMemberCount = computed(() => {
  const today = dayjs().format('MM-DD');
  return customerStore.customers.filter(c => c.isMember && c.birthday && dayjs(c.birthday).format('MM-DD') === today).length;
});

// 数字滚动动画组合式函数
function useCountUp(target, duration = 800) {
  const display = ref(0);
  let timer = null;
  watch(target, (val) => {
    if (timer) clearInterval(timer);
    const start = display.value;
    const end = Number(val);
    if (start === end) return;
    const step = Math.ceil((end - start) / (duration / 16));
    timer = setInterval(() => {
      if ((step > 0 && display.value < end) || (step < 0 && display.value > end)) {
        display.value += step;
        if ((step > 0 && display.value > end) || (step < 0 && display.value < end)) {
          display.value = end;
        }
      } else {
        display.value = end;
        clearInterval(timer);
      }
    }, 16);
  }, { immediate: true });
  return display;
}
// 包裹所有数字
const animatedPendingOrderCount = useCountUp(pendingOrderCount);
const animatedLowStockCount = useCountUp(lowStockCount);
const animatedPendingFeedbackCount = useCountUp(pendingFeedbackCount);
const animatedTodayBirthdayMemberCount = useCountUp(todayBirthdayMemberCount);

// 高亮动画逻辑
const highlightOrder = ref(false);
const highlightStock = ref(false);
const highlightFeedback = ref(false);
const highlightBirthday = ref(false);

watch(pendingOrderCount, async (val, oldVal) => {
  if (val !== oldVal) {
    highlightOrder.value = true;
    await nextTick();
    setTimeout(() => highlightOrder.value = false, 1000);
  }
});
watch(lowStockCount, async (val, oldVal) => {
  if (val !== oldVal) {
    highlightStock.value = true;
    await nextTick();
    setTimeout(() => highlightStock.value = false, 1000);
  }
});
watch(pendingFeedbackCount, async (val, oldVal) => {
  if (val !== oldVal) {
    highlightFeedback.value = true;
    await nextTick();
    setTimeout(() => highlightFeedback.value = false, 1000);
  }
});
watch(todayBirthdayMemberCount, async (val, oldVal) => {
  if (val !== oldVal) {
    highlightBirthday.value = true;
    await nextTick();
    setTimeout(() => highlightBirthday.value = false, 1000);
  }
});

onMounted(() => {
  fetchLowStock();
  const chart = echarts.init(orderChart.value);
  chart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 30, right: 20, top: 30, bottom: 30 },
    xAxis: {
      type: 'category',
      data: ['周一','周二','周三','周四','周五','周六','周日'],
      axisLine: { lineStyle: { color: '#dbeafe' } },
      axisLabel: { color: '#666' }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      splitLine: { lineStyle: { color: '#f0f1f2' } },
      axisLabel: { color: '#666' }
    },
    series: [{
      name: '订单数',
      type: 'line',
      data: [22, 25, 19, 28, 30, 27, 28],
      smooth: true,
      symbol: 'circle',
      symbolSize: 10,
      lineStyle: { color: '#1976d2', width: 3 },
      itemStyle: { color: '#1976d2' },
      areaStyle: { color: 'rgba(25,118,210,0.08)' }
    }]
  });
});

function go(name) {
  // 跳转到对应页面
  switch (name) {
    case 'customer': router.push('/manager/customer'); break;
    case 'service': router.push('/manager/service'); break;
    case 'inventory': router.push('/manager/inventory'); break;
    case 'employee': router.push('/manager/employee'); break;
    case 'system': router.push('/manager/system'); break;
    // 未配置的页面跳转到404
    default: break;
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.dashboard-announcement {
  margin-bottom: 16px;
}
.dashboard-title {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  margin-bottom: 24px;
}
.dashboard-main {
  display: flex;
  gap: 24px;
}
.dashboard-main-left {
  flex: 1 1 0%;
  min-width: 0;
}
.dashboard-main-right {
  width: 320px;
  min-width: 260px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}
.dashboard-card {
  border-radius: 12px;
  padding: 24px 16px 16px 16px;
  min-width: 0;
  transition: box-shadow 0.2s, transform 0.2s, border-color 0.2s;
}
.dashboard-card:hover {
  box-shadow: 0 6px 24px 0 rgba(60,120,240,0.10);
  transform: translateY(-6px) scale(1.03);
  z-index: 2;
}
.dashboard-card-blue:hover { border-color: #1976d2; }
.dashboard-card-green:hover { border-color: #388e3c; }
.dashboard-card-yellow:hover { border-color: #fbc02d; }
.dashboard-card-red:hover { border-color: #d32f2f; }
.dashboard-card-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}
.dashboard-card-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 4px;
}
.dashboard-card-desc {
  font-size: 14px;
  color: #666;
}
.dashboard-card-blue {
  background: #e8f3ff;
  border: 1px solid #b3d8fd;
  color: #1976d2;
}
.dashboard-card-green {
  background: #e8fbe8;
  border: 1px solid #b7e4c7;
  color: #388e3c;
}
.dashboard-card-yellow {
  background: #fffbe8;
  border: 1px solid #ffe082;
  color: #fbc02d;
}
.dashboard-card-red {
  background: #ffeaea;
  border: 1px solid #ffb3b3;
  color: #d32f2f;
}
.dashboard-chart {
  margin-bottom: 32px;
  border-radius: 12px;
  padding: 20px 24px 8px 24px;
}
.dashboard-chart-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
}
.dashboard-echart {
  width: 100%;
  height: 220px;
}
.dashboard-actions-card {
  margin-bottom: 24px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.dashboard-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.dashboard-action-row {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}
.action-btn {
  flex: 1;
  border-radius: 8px;
  font-weight: 500;
  font-size: 16px;
  height: 44px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.03);
  transition: background 0.2s, color 0.2s;
}
.action-btn.blue { background: #e3f0ff; color: #1976d2; }
.action-btn.green { background: #e6f7e6; color: #43a047; }
.action-btn.orange { background: #fff3e0; color: #fb8c00; }
.action-btn.purple { background: #f3e8ff; color: #8e24aa; }
.action-btn.teal { background: #e0f7fa; color: #00838f; }
.action-btn.pink { background: #fce4ec; color: #d81b60; }
.action-btn.yellow { background: #fffde7; color: #fbc02d; }
.action-btn.gray { background: #f5f5f5; color: #757575; }
.action-btn:hover {
  filter: brightness(0.95);
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.dashboard-right-col {
  display: flex;
  flex-direction: column;
  gap: 24px;
  align-items: center;
}
.dashboard-side-img {
  width: 220px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.dashboard-todo {
  border-radius: 12px;
  margin-bottom: 0;
}
.dashboard-todo-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
}
.dashboard-todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.dashboard-todo-list li {
  font-size: 15px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  transition: background 0.3s, box-shadow 0.3s, transform 0.2s;
  cursor: pointer;
}
.dashboard-todo-list li:hover {
  background: #f0f7ff;
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.10);
  transform: scale(1.03);
}
.todo-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
}
.todo-blue { background: #1976d2; }
.todo-red { background: #d32f2f; }
.todo-yellow { background: #fbc02d; }
.todo-green { background: #388e3c; }
.highlight {
  animation: highlight-fade 1s;
  background: #fffbe8;
  transition: background 0.5s;
}
@keyframes highlight-fade {
  0% { background: #fffbe8; }
  100% { background: transparent; }
}
</style>
